package org.review.datastructure;

import java.util.Objects;

public class HashLinkedList {

    public static void main(String[] args) {
        HashLinkedList hashTable = new HashLinkedList(5);
        for (int i = 0; i < 100; i++) {
            hashTable.add(new Employee("张" + i, i));
        }
        hashTable.list();


        for (int i = 0; i < 10; i++) {
            Employee employeeById = hashTable.findEmployeeById(i);
            System.out.println(employeeById);
        }
    }

    private int size;
    private EmplLinkList[] emplLinkList;

    public HashLinkedList(int size) {
        this.size = size;
        emplLinkList = new EmplLinkList[size];
        for (int i = 0; i < size; i++) {
            emplLinkList[i] = new EmplLinkList();
        }
    }

    public int hashNo(int no) {
        return no % size;

    }

    public void add(Employee employee) {
        int i = hashNo(employee.id);
        emplLinkList[i].addEmpl(employee);
    }

    public Employee findEmployeeById(int id) {
        int linkListNo = hashNo(id);
        return emplLinkList[linkListNo].findEmployeeById(id);
    }

    public void list() {
        for (int i = 0; i < size; i++) {
            emplLinkList[i].list(i);
        }
    }

    class EmplLinkList {
        private Employee head;

        public void list(int no) {
            Employee current = head;
            if (head == null) {
                System.out.println("第 " + (no + 1) + " 链表为空");
                return;
            }

            System.out.print("第 " + (no + 1) + " 链表为 ");
            while (current != null) {
                System.out.printf(" => id=%d name=%s\t", current.id, current.name);
                current = current.next;
            }
            System.out.println();
        }

        public void addEmpl(Employee employee) {
            if (Objects.isNull(head)) {
                head = employee;
                return;
            }
            Employee current = head;
            while (current.next != null) {
                current = current.next;
            }
            current.next = employee;
        }

        public Employee findEmployeeById(int employeeNo) {
            Employee current = head;

            while (current != null) {
                if (current.id == employeeNo) {
                    return current;
                }
                current = current.next;
            }
            return null;
        }
    }
}


class Employee {
    String name;
    int id;

    Employee next;

    public Employee(String name, int id) {
        this.name = name;
        this.id = id;

    }

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", id=" + id +
                '}';
    }
}